import asyncio
import base64
import pathlib

from asyncio import Queue

import cv2
import easydict

import cjc.project_setting
from cjc import project_setting
from  cjc.tools.cv2_base64 import base64_to_cv2_image
from cjc.tools.memory_share_helper import MemoryShareHelper
from cjc.tools.memory_share_helper_ubuntu import MemoryShareUbuntuHelper


def get_track_queue_count():
    if track_queue is None:
        return 0
    return track_queue.qsize()


async def get_data_from_queue():
    """从队列中获取"""
    await asyncio.sleep(0)
    t = None
    try:
        if track_queue is None:
            return None
        if track_queue is not None and not track_queue.empty():
            t = track_queue.get(block=False)
    except BaseException as e:
        print("get_data_from_queue出错：", e)
    return t

track_queue = None

memory_share_helper = MemoryShareUbuntuHelper()

msg_queue = Queue(100)
webapi_msg_queue = Queue(100)


async def put_webapi_msg_to_queue(filepath, mp):

    src_path = pathlib.Path(filepath)
    src_name = src_path.name
    cover_name = src_path.stem + '.jpg'
    src_path = src_path.absolute()
    src_content = open(str(src_path), 'rb').read()
    # print("上传资料",type( src_content))
    # print(len(src_content))

    _dict = easydict.EasyDict(proj_id=project_setting.project_id,
                              src_name=src_name,
                              cover_name=cover_name,
                              cover_content=base64.b64decode(mp.img),
                              src_content=src_content,
                              track=mp.track)
    await webapi_msg_queue.put(_dict)


async def get_webapi_msg_from_queue():
    if webapi_msg_queue.empty():
        return None
    return await webapi_msg_queue.get()


async def put_message_to_queue(msg):
    if msg_queue.full():
        await msg_queue.get()
    await msg_queue.put(msg)

last_video_file = ""


def check_video_file_name_changed():
    """没用了可以删除"""
    global last_video_file
    txt_lst = memory_share_helper.read_txt_list_from_memory()

    if isinstance(txt_lst, list) and len(txt_lst) > 1:
        print(txt_lst)
        fname = txt_lst[0]
        if fname != last_video_file:
            tmp = last_video_file
            last_video_file = fname
            print("内存中读取数据内容：", txt_lst)
            return True, tmp
    return False, None


def set_q(tq):
    global track_queue
    track_queue = tq
